package com.foreknow.service;

import com.foreknow.dao.impl.UserDaoImpl;
import com.foreknow.entity.User;

import java.sql.SQLException;

public class UserService1 {
    private UserDaoImpl userDaoImpl;

    public UserService1(){
        userDaoImpl = new UserDaoImpl();
    }

    public boolean signIn(String username,String password){
        String sql = "select * from user where username like ? or email like ? or account like ? or phone like ?";
        Object[] params = {username,username,username,username};
        User user = null;
        try {
            user = userDaoImpl.queryOne(sql,params);
            return password.equals(user.getPassword());
        } catch (SQLException e) {
            e.printStackTrace();
            return false;
        }
    }

    public boolean signUp(User user){
        String sql = "insert into user(username,account,password,phone,email,avatar) values(?,?,?,?,?,?)";
        Object[] params = {user.getUsername(),user.getAccount(),user.getPassword(),user.getPhone(),user.getEmail(),user.getAvatar()};
        try {
            return userDaoImpl.insert(sql,params) > 0;
        } catch (SQLException e) {
            e.printStackTrace();
            return false;
        }
    }

    public User getUserByID(Integer id){
        String sql = "select * from user where id=?";
        try {
            return userDaoImpl.queryOne(sql,id);
        } catch (SQLException e) {
            e.printStackTrace();
            return null;
        }
    }

    public User getUserByName(String username){
        String sql = "select * from user where username like ? or email like ? or account like ? or phone like ?";
        Object[] params = {username,username,username,username};
        try {
            return userDaoImpl.queryOne(sql,params);
        } catch (SQLException e) {
            e.printStackTrace();
            return null;
        }
    }

    public Integer updateUser(User user){
        String sql = "update user set username = ?,account = ?,password = ?,phone = ?,email = ? where id = ?";
        try {
            return userDaoImpl.update(sql,user.getUsername(),user.getAccount(),user.getPassword(),user.getPhone(),user.getEmail(),user.getId());
        } catch (SQLException e) {
            e.printStackTrace();
            return -1;
        }
    }
}